﻿using System.Globalization;

namespace Sage.Data.Extensions
{
    /// <summary>
    /// 字典扩展方法
    /// 完全兼容 AOT (Ahead-of-Time) 编译
    /// </summary>
    public static class DictionaryExtensions
    {
        #region 字符串转换方法

        /// <summary>
        /// 将字典转换为查询字符串（URL编码）
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <param name="urlEncode">是否进行URL编码</param>
        /// <returns>查询字符串</returns>
        /// <exception cref="ArgumentNullException">当 parameters 为 null 时抛出</exception>
        public static string ToQueryString(this Dictionary<string, object> parameters, bool urlEncode = true)
        {
            ArgumentNullException.ThrowIfNull(parameters);

            if (parameters.Count == 0) return string.Empty;

            var queryParts = parameters.Select(kvp =>
            {
                var value = kvp.Value?.ToString() ?? "";
                var encodedKey = urlEncode ? Uri.EscapeDataString(kvp.Key) : kvp.Key;
                var encodedValue = urlEncode ? Uri.EscapeDataString(value) : value;
                return $"{encodedKey}={encodedValue}";
            });

            return string.Join("&", queryParts);
        }

        /// <summary>
        /// 将SortedDictionary转换为查询字符串（URL编码）
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <param name="urlEncode">是否进行URL编码</param>
        /// <returns>查询字符串</returns>
        /// <exception cref="ArgumentNullException">当 parameters 为 null 时抛出</exception>
        public static string ToQueryString(this SortedDictionary<string, object> parameters, bool urlEncode = true)
        {
            ArgumentNullException.ThrowIfNull(parameters);

            if (parameters.Count == 0) return string.Empty;

            var queryParts = parameters.Select(kvp =>
            {
                var value = kvp.Value?.ToString() ?? "";
                var encodedKey = urlEncode ? Uri.EscapeDataString(kvp.Key) : kvp.Key;
                var encodedValue = urlEncode ? Uri.EscapeDataString(value) : value;
                return $"{encodedKey}={encodedValue}";
            });

            return string.Join("&", queryParts);
        }

        /// <summary>
        /// 将字典转换为表单字符串（不进行URL编码）
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <returns>表单字符串</returns>
        /// <exception cref="ArgumentNullException">当 parameters 为 null 时抛出</exception>
        public static string ToFormString(this Dictionary<string, object> parameters)
        {
            return parameters.ToQueryString(false);
        }

        /// <summary>
        /// 将SortedDictionary转换为表单字符串（不进行URL编码）
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <returns>表单字符串</returns>
        /// <exception cref="ArgumentNullException">当 parameters 为 null 时抛出</exception>
        public static string ToFormString(this SortedDictionary<string, object> parameters)
        {
            return parameters.ToQueryString(false);
        }

        /// <summary>
        /// 将字典转换为JSON格式字符串（简单实现）
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <returns>JSON字符串</returns>
        /// <exception cref="ArgumentNullException">当 parameters 为 null 时抛出</exception>
        public static string ToJsonString(this Dictionary<string, object> parameters)
        {
            ArgumentNullException.ThrowIfNull(parameters);

            if (parameters.Count == 0) return "{}";

            var jsonParts = parameters.Select(kvp =>
            {
                var key = $"\"{EscapeJsonString(kvp.Key)}\"";
                var value = FormatJsonValue(kvp.Value);
                return $"{key}:{value}";
            });

            return "{" + string.Join(",", jsonParts) + "}";
        }

        /// <summary>
        /// 将SortedDictionary转换为JSON格式字符串（简单实现）
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <returns>JSON字符串</returns>
        /// <exception cref="ArgumentNullException">当 parameters 为 null 时抛出</exception>
        public static string ToJsonString(this SortedDictionary<string, object> parameters)
        {
            ArgumentNullException.ThrowIfNull(parameters);

            if (parameters.Count == 0) return "{}";

            var jsonParts = parameters.Select(kvp =>
            {
                var key = $"\"{EscapeJsonString(kvp.Key)}\"";
                var value = FormatJsonValue(kvp.Value);
                return $"{key}:{value}";
            });

            return "{" + string.Join(",", jsonParts) + "}";
        }

        /// <summary>
        /// 格式化JSON值
        /// </summary>
        /// <param name="value">要格式化的值</param>
        /// <returns>格式化后的JSON字符串</returns>
        private static string FormatJsonValue(object? value)
        {
            return value switch
            {
                null => "null",
                string s => $"\"{EscapeJsonString(s)}\"",
                bool b => b.ToString().ToLowerInvariant(),
                int => value.ToString()!,
                long => value.ToString()!,
                float f => f.ToString("G", CultureInfo.InvariantCulture),
                double d => d.ToString("G", CultureInfo.InvariantCulture),
                decimal m => m.ToString(CultureInfo.InvariantCulture),
                DateTime dt => $"\"{dt:yyyy-MM-ddTHH:mm:ss.fffZ}\"",
                Guid g => $"\"{g}\"",
                IEnumerable<object> collection => FormatJsonArray(collection),
                _ => $"\"{EscapeJsonString(value?.ToString() ?? "")}\""
            };
        }

        /// <summary>
        /// 格式化JSON数组
        /// </summary>
        /// <param name="collection">集合</param>
        /// <returns>JSON数组字符串</returns>
        private static string FormatJsonArray(IEnumerable<object> collection)
        {
            var items = collection.Select(FormatJsonValue);
            return "[" + string.Join(",", items) + "]";
        }

        /// <summary>
        /// 转义JSON字符串中的特殊字符
        /// </summary>
        /// <param name="str">要转义的字符串</param>
        /// <returns>转义后的字符串</returns>
        private static string EscapeJsonString(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;

            return str.Replace("\\", "\\\\")
                      .Replace("\"", "\\\"")
                      .Replace("\n", "\\n")
                      .Replace("\r", "\\r")
                      .Replace("\t", "\\t")
                      .Replace("\b", "\\b")
                      .Replace("\f", "\\f");
        }

        #endregion

        #region 字典操作方法

        /// <summary>
        /// 安全获取字典值
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="dictionary">字典</param>
        /// <param name="key">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>值或默认值</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static T GetValueOrDefault<T>(this Dictionary<string, object> dictionary, string key, T defaultValue = default!)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dictionary.TryGetValue(key, out var value) && value is T result)
                return result;

            return defaultValue;
        }

        /// <summary>
        /// 批量添加参数
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="parameters">要添加的参数</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 parameters 为 null 时抛出</exception>
        public static Dictionary<string, object> AddRange(this Dictionary<string, object> dictionary, Dictionary<string, object> parameters)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(parameters);

            foreach (var (key, value) in parameters)
            {
                dictionary[key] = value;
            }

            return dictionary;
        }

        /// <summary>
        /// 移除空值参数
        /// </summary>
        /// <param name="dictionary">字典</param>
        /// <returns>移除空值后的新字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static Dictionary<string, object> RemoveEmptyValues(this Dictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);

            return dictionary.Where(kvp => kvp.Value switch
            {
                null => false,
                string s => !string.IsNullOrWhiteSpace(s),
                IEnumerable<object> collection => collection.Any(),
                Array array => array.Length > 0,
                Guid g => g != Guid.Empty,
                _ => true
            }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }

        #endregion

        #region 基础条件添加方法

        /// <summary>
        /// 当引用类型值不为 null 时，添加键值对到字典
        /// </summary>
        /// <typeparam name="T">值的类型，必须是引用类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotNull<T>(
            this Dictionary<string, object> dictionary,
            string key,
            T? value) where T : class
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value is not null)
            {
                dictionary[key] = value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当可空值类型有值时，添加键值对到字典
        /// </summary>
        /// <typeparam name="T">值的类型，必须是值类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的可空值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfHasValue<T>(
            this Dictionary<string, object> dictionary,
            string key,
            T? value) where T : struct
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue)
            {
                dictionary[key] = value.Value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当字符串不为 null、空字符串或仅包含空白字符时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的字符串值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string key,
            string? value)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (!string.IsNullOrWhiteSpace(value))
            {
                dictionary[key] = value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当字符串不为 null 或空字符串时，添加键值对到字典（允许仅包含空白字符的字符串）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的字符串值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotNullOrEmpty(
            this Dictionary<string, object> dictionary,
            string key,
            string? value)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (!string.IsNullOrEmpty(value))
            {
                dictionary[key] = value;
            }

            return dictionary;
        }

        #endregion

        #region 自定义条件验证方法

        /// <summary>
        /// 当可空值类型满足条件时，转换后添加到字典（可处理枚举）
        /// </summary>
        /// <typeparam name="TSource">源值类型</typeparam>
        /// <typeparam name="TTarget">目标值类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的可空值</param>
        /// <param name="condition">验证条件</param>
        /// <param name="converter">值转换函数</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        public static Dictionary<string, object> AddIfValid<TSource, TTarget>(
            this Dictionary<string, object> dictionary,
            string key,
            TSource? value,
            Func<TSource?, bool> condition,
            Func<TSource?, TTarget> converter) where TSource : struct
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentNullException.ThrowIfNull(condition);
            ArgumentNullException.ThrowIfNull(converter);

            if (condition(value))
            {
                dictionary[key] = converter(value)!;
            }

            return dictionary;
        }

        /// <summary>
        /// 当引用类型值满足自定义条件时，添加键值对到字典
        /// </summary>
        /// <typeparam name="T">值的类型，必须是引用类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的值</param>
        /// <param name="condition">自定义验证条件，当返回 true 时添加键值对</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、key 或 condition 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValid<T>(
            this Dictionary<string, object> dictionary,
            string key,
            T? value,
            Func<T?, bool> condition) where T : class
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentNullException.ThrowIfNull(condition);

            if (condition(value) && value is not null)
            {
                dictionary[key] = value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当可空值类型满足自定义条件时，添加键值对到字典
        /// </summary>
        /// <typeparam name="T">值的类型，必须是值类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的可空值</param>
        /// <param name="condition">自定义验证条件，当返回 true 时添加键值对</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、key 或 condition 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValid<T>(
            this Dictionary<string, object> dictionary,
            string key,
            T? value,
            Func<T?, bool> condition) where T : struct
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentNullException.ThrowIfNull(condition);

            if (condition(value) && value.HasValue)
            {
                dictionary[key] = value.Value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当对象满足自定义条件时，添加键值对到字典（无类型约束版本）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的值</param>
        /// <param name="condition">自定义验证条件，当返回 true 时添加键值对</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、key 或 condition 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValid(
            this Dictionary<string, object> dictionary,
            string key,
            object? value,
            Func<object?, bool> condition)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentNullException.ThrowIfNull(condition);

            if (condition(value) && value is not null)
            {
                dictionary[key] = value;
            }

            return dictionary;
        }

        #endregion

        #region 数值类型专用方法

        /// <summary>
        /// 当整数值大于指定最小值时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的整数值</param>
        /// <param name="minValue">最小值（不包含），默认为 0</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfGreaterThan(
            this Dictionary<string, object> dictionary,
            string key,
            int? value,
            int minValue = 0)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue && value.Value > minValue)
            {
                dictionary[key] = value.Value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当长整数值大于指定最小值时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的长整数值</param>
        /// <param name="minValue">最小值（不包含），默认为 0</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfGreaterThan(
            this Dictionary<string, object> dictionary,
            string key,
            long? value,
            long minValue = 0L)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue && value.Value > minValue)
            {
                dictionary[key] = value.Value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当小数值大于指定最小值时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的小数值</param>
        /// <param name="minValue">最小值（不包含），默认为 0.0</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfGreaterThan(
            this Dictionary<string, object> dictionary,
            string key,
            decimal? value,
            decimal minValue = 0.0m)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue && value.Value > minValue)
            {
                dictionary[key] = value.Value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当整数值在指定范围内时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的整数值</param>
        /// <param name="minValue">最小值（包含）</param>
        /// <param name="maxValue">最大值（包含）</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        /// <exception cref="ArgumentException">当 minValue 大于 maxValue 时抛出</exception>
        public static Dictionary<string, object> AddIfInRange(
            this Dictionary<string, object> dictionary,
            string key,
            int? value,
            int minValue,
            int maxValue)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (minValue > maxValue)
                throw new ArgumentException($"最小值 ({minValue}) 不能大于最大值 ({maxValue})", nameof(minValue));

            if (value.HasValue && value.Value >= minValue && value.Value <= maxValue)
            {
                dictionary[key] = value.Value;
            }

            return dictionary;
        }

        #endregion

        #region 集合类型专用方法

        /// <summary>
        /// 当集合不为 null 且包含元素时，添加键值对到字典
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="collection">要添加的集合</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotEmpty<T>(
            this Dictionary<string, object> dictionary,
            string key,
            IEnumerable<T>? collection)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (collection is not null && collection.Any())
            {
                dictionary[key] = collection;
            }

            return dictionary;
        }

        /// <summary>
        /// 当数组不为 null 且包含元素时，添加键值对到字典
        /// </summary>
        /// <typeparam name="T">数组元素类型</typeparam>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="array">要添加的数组</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotEmpty<T>(
            this Dictionary<string, object> dictionary,
            string key,
            T[]? array)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (array is not null && array.Length > 0)
            {
                dictionary[key] = array;
            }

            return dictionary;
        }

        #endregion

        #region 日期时间专用方法

        /// <summary>
        /// 当日期时间值不为 null 且不等于默认值时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTime">要添加的日期时间值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotDefault(
            this Dictionary<string, object> dictionary,
            string key,
            DateTime? dateTime)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTime.HasValue && dateTime.Value != default)
            {
                dictionary[key] = dateTime.Value;
            }

            return dictionary;
        }

        /// <summary>
        /// 当日期时间值不为 null、不等于默认值且在指定日期之后时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTime">要添加的日期时间值</param>
        /// <param name="afterDate">指定的最早日期</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfAfter(
            this Dictionary<string, object> dictionary,
            string key,
            DateTime? dateTime,
            DateTime afterDate)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTime.HasValue && dateTime.Value > afterDate)
            {
                dictionary[key] = dateTime.Value;
            }

            return dictionary;
        }
        #endregion

        #region 日期时间范围专用方法

        /// <summary>
        /// 当日期时间范围集合包含正好两个元素（开始和结束时间）时，添加键值对到字典（IEnumerable版本，兼容List、Array等）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTimeRange">日期时间范围集合，必须包含正好2个元素</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValidDateRange(
            this Dictionary<string, object> dictionary,
            string key,
            IEnumerable<string>? dateTimeRange)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTimeRange is null)
                return dictionary;

            // 优化：根据类型直接获取计数，避免多次枚举
            var count = dateTimeRange switch
            {
                string[] array => array.Length,
                ICollection<string> collection => collection.Count,
                _ => dateTimeRange.Count()
            };

            if (count == 2)
            {
                // 统一转换为数组类型，确保类型一致性
                var result = dateTimeRange switch
                {
                    string[] array => array,
                    List<string> list => [.. list],
                    _ => [.. dateTimeRange]
                };

                dictionary[key] = result;
            }

            return dictionary;
        }

        /// <summary>
        /// 当日期时间范围数组包含正好两个元素（开始和结束时间）时，添加键值对到字典（Array专用版本）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTimeRange">日期时间范围数组，必须包含正好2个元素</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValidDateRange(
            this Dictionary<string, object> dictionary,
            string key,
            string[]? dateTimeRange)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTimeRange is not null && dateTimeRange.Length == 2)
            {
                dictionary[key] = dateTimeRange;
            }

            return dictionary;
        }

        /// <summary>
        /// 当日期时间范围列表包含正好两个元素（开始和结束时间）时，添加键值对到字典（List专用版本）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTimeRange">日期时间范围列表，必须包含正好2个元素</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValidDateRange(
            this Dictionary<string, object> dictionary,
            string key,
            List<string>? dateTimeRange)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTimeRange is not null && dateTimeRange.Count == 2)
            {
                dictionary[key] = dateTimeRange;
            }

            return dictionary;
        }

        /// <summary>
        /// 当日期时间范围集合包含正好两个有效的日期时间字符串时，添加键值对到字典（带验证版本）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTimeRange">日期时间范围集合，必须包含正好2个有效的日期时间字符串</param>
        /// <param name="validateDateTime">是否验证日期时间格式的有效性，默认为true</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValidDateRange(
            this Dictionary<string, object> dictionary,
            string key,
            IEnumerable<string>? dateTimeRange,
            bool validateDateTime)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTimeRange is null)
                return dictionary;

            // 转换为数组以便后续处理
            string[] elements;
            int count;

            switch (dateTimeRange)
            {
                case string[] array:
                    elements = array;
                    count = array.Length;
                    break;
                case List<string> list:
                    elements = [.. list];
                    count = list.Count;
                    break;
                case ICollection<string> collection:
                    elements = [.. collection];
                    count = collection.Count;
                    break;
                default:
                    elements = [.. dateTimeRange];
                    count = elements.Length;
                    break;
            }

            if (count != 2)
                return dictionary;

            // 如果不需要验证日期时间格式，直接添加
            if (!validateDateTime)
            {
                dictionary[key] = elements;
                return dictionary;
            }

            // 验证两个日期时间字符串是否都有效且不为空
            bool isValid = elements.All(dt =>
                !string.IsNullOrWhiteSpace(dt) &&
                DateTime.TryParse(dt, out _));

            if (isValid)
            {
                dictionary[key] = elements;
            }

            return dictionary;
        }

        /// <summary>
        /// 当日期时间范围集合包含正好两个有效的日期时间字符串且开始时间早于结束时间时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="dateTimeRange">日期时间范围集合，必须包含正好2个有效的日期时间字符串</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfValidDateRangeWithOrder(
            this Dictionary<string, object> dictionary,
            string key,
            IEnumerable<string>? dateTimeRange)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (dateTimeRange is null)
                return dictionary;

            // 转换为数组以便后续处理
            string[] elements;
            int count;

            switch (dateTimeRange)
            {
                case string[] array:
                    elements = array;
                    count = array.Length;
                    break;
                case List<string> list:
                    elements = [.. list];
                    count = list.Count;
                    break;
                case ICollection<string> collection:
                    elements = [.. collection];
                    count = collection.Count;
                    break;
                default:
                    elements = [.. dateTimeRange];
                    count = elements.Length;
                    break;
            }

            if (count != 2)
                return dictionary;

            // 验证两个日期时间字符串是否都有效且不为空
            if (elements.Any(dt => string.IsNullOrWhiteSpace(dt)))
                return dictionary;

            if (DateTime.TryParse(elements[0], out var startTime) &&
                DateTime.TryParse(elements[1], out var endTime))
            {
                // 确保开始时间早于或等于结束时间
                if (startTime <= endTime)
                {
                    dictionary[key] = elements;
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 创建标准的日期时间范围（从开始和结束日期时间创建字符串数组）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="startDateTime">开始日期时间</param>
        /// <param name="endDateTime">结束日期时间</param>
        /// <param name="format">日期时间格式，默认为 "yyyy-MM-dd HH:mm:ss"</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddDateTimeRange(
            this Dictionary<string, object> dictionary,
            string key,
            DateTime? startDateTime,
            DateTime? endDateTime,
            string format = "yyyy-MM-dd HH:mm:ss")
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentNullException.ThrowIfNull(format);

            if (startDateTime.HasValue && endDateTime.HasValue && startDateTime.Value <= endDateTime.Value)
            {
                var dateRange = new string[]
                {
            startDateTime.Value.ToString(format),
            endDateTime.Value.ToString(format)
                };
                dictionary[key] = dateRange;
            }

            return dictionary;
        }

        #endregion

        #region GUID 专用方法

        /// <summary>
        /// 当 GUID 值不为 null 且不等于空 GUID 时，添加键值对到字典
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="guid">要添加的 GUID 值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string key,
            Guid? guid)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (guid.HasValue && guid.Value != Guid.Empty)
            {
                dictionary[key] = guid.Value;
            }

            return dictionary;
        }

        #endregion

        #region 批量添加方法

        /// <summary>
        /// 批量添加键值对，只添加满足条件的项
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="items">要添加的键值对集合</param>
        /// <param name="condition">验证条件，当返回 true 时添加该键值对</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、items 或 condition 为 null 时抛出</exception>
        public static Dictionary<string, object> AddRangeIf(
            this Dictionary<string, object> dictionary,
            IEnumerable<KeyValuePair<string, object?>> items,
            Func<KeyValuePair<string, object?>, bool> condition)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(items);
            ArgumentNullException.ThrowIfNull(condition);

            foreach (var item in items.Where(condition))
            {
                if (item.Value is not null)
                {
                    dictionary[item.Key] = item.Value;
                }
            }

            return dictionary;
        }

        #endregion

        #region 实用工具方法

        /// <summary>
        /// 尝试添加键值对到字典，如果键已存在则不添加
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的值</param>
        /// <returns>如果成功添加返回 true，否则返回 false</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、key 或 value 为 null 时抛出</exception>
        public static bool TryAdd(this Dictionary<string, object> dictionary, string key, object value)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);
            ArgumentNullException.ThrowIfNull(value);

            if (!dictionary.ContainsKey(key))
            {
                dictionary[key] = value;
                return true;
            }

            return false;
        }

        /// <summary>
        /// 安全地尝试添加键值对到字典，允许 null 值
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的值（可以为 null）</param>
        /// <returns>如果成功添加返回 true，否则返回 false</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static bool TryAddSafe(this Dictionary<string, object> dictionary, string key, object? value)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (!dictionary.ContainsKey(key))
            {
                dictionary[key] = value!;
                return true;
            }

            return false;
        }

        #endregion

        #region 布尔类型专用方法

        /// <summary>
        /// 当布尔值不为 null 时，添加键值对到字典（true=1, false=0）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的布尔值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddBoolAsInt(
            this Dictionary<string, object> dictionary,
            string key,
            bool? value)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue)
            {
                dictionary[key] = value.Value ? 1 : 0;
            }

            return dictionary;
        }

        /// <summary>
        /// 当布尔值不为 null 时，添加键值对到字典（true="1", false="0"）
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">要添加的布尔值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddBoolAsString(
            this Dictionary<string, object> dictionary,
            string key,
            bool? value)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue)
            {
                dictionary[key] = value.Value ? "1" : "0";
            }

            return dictionary;
        }

        /// <summary>
        /// 当布尔值为 true 时添加指定值，为 false 时添加另一个值
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="key">键名</param>
        /// <param name="value">布尔值</param>
        /// <param name="trueValue">为 true 时添加的值</param>
        /// <param name="falseValue">为 false 时添加的值</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 key 为 null 时抛出</exception>
        public static Dictionary<string, object> AddBoolAsValue<T>(
            this Dictionary<string, object> dictionary,
            string key,
            bool? value,
            T trueValue,
            T falseValue)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(key);

            if (value.HasValue)
            {
                dictionary[key] = value.Value ? trueValue! : falseValue!;
            }

            return dictionary;
        }

        #endregion

        #region 索引数组参数专用方法 (AOT 兼容)

        /// <summary>
        /// 将字符串数组作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 string[] 专用版本
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的字符串数组</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// dict.AddIndexedArray("coupon_id", new[] { "123", "456" });
        /// // 结果: coupon_id[0] = "123", coupon_id[1] = "456"
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            string[]? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Length == 0)
                return dictionary;

            for (int i = 0; i < values.Length; i++)
            {
                if (values[i] is not null)
                {
                    dictionary[$"{keyPrefix}[{i}]"] = values[i];
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 将字符串列表作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 List&lt;string&gt; 专用版本
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的字符串列表</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// var couponIds = new List&lt;string&gt; { "123", "456" };
        /// dict.AddIndexedArray("coupon_id", couponIds);
        /// // 结果: coupon_id[0] = "123", coupon_id[1] = "456"
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            List<string>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            for (int i = 0; i < values.Count; i++)
            {
                if (values[i] is not null)
                {
                    dictionary[$"{keyPrefix}[{i}]"] = values[i];
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 将整数数组作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 int[] 专用版本
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数数组</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// dict.AddIndexedArray("category_id", new[] { 1, 2, 3 });
        /// // 结果: category_id[0] = 1, category_id[1] = 2, category_id[2] = 3
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            int[]? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Length == 0)
                return dictionary;

            for (int i = 0; i < values.Length; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 将整数列表作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 List&lt;int&gt; 专用版本
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数列表</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// var ids = new List&lt;int&gt; { 1, 2, 3 };
        /// dict.AddIndexedArray("id", ids);
        /// // 结果: id[0] = 1, id[1] = 2, id[2] = 3
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            List<int>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            for (int i = 0; i < values.Count; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 将长整数数组作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 long[] 专用版本
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的长整数数组</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            long[]? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Length == 0)
                return dictionary;

            for (int i = 0; i < values.Length; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 将长整数列表作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 List&lt;long&gt; 专用版本
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的长整数列表</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            List<long>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            for (int i = 0; i < values.Count; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 将 IList&lt;string&gt; 作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 IList&lt;string&gt; 专用版本，兼容各种 string 列表实现
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的字符串列表接口</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            IList<string>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            for (int i = 0; i < values.Count; i++)
            {
                if (values[i] is not null)
                {
                    dictionary[$"{keyPrefix}[{i}]"] = values[i];
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 将 IList&lt;int&gt; 作为索引数组参数添加到字典中（如 key[0], key[1], key[2]...）
        /// AOT 优化的 IList&lt;int&gt; 专用版本，兼容各种 int 列表实现
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数列表接口</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArray(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            IList<int>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            for (int i = 0; i < values.Count; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        #endregion

        #region 索引数组参数条件添加方法 (AOT 兼容)

        /// <summary>
        /// 当字符串数组不为 null 且包含元素时，将其作为索引数组参数添加到字典中
        /// 过滤掉 null 和空白字符串
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的字符串数组</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// dict.AddIndexedArrayIfNotEmpty("coupon_id", new[] { "123", "", "456", null });
        /// // 结果: coupon_id[0] = "123", coupon_id[1] = "456" (空字符串和null被过滤)
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArrayIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            string[]? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Length == 0)
                return dictionary;

            // 过滤掉空字符串和null，同时记录有效元素的索引
            int index = 0;
            for (int i = 0; i < values.Length; i++)
            {
                if (!string.IsNullOrWhiteSpace(values[i]))
                {
                    dictionary[$"{keyPrefix}[{index}]"] = values[i];
                    index++;
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 当字符串列表不为 null 且包含元素时，将其作为索引数组参数添加到字典中
        /// 过滤掉 null 和空白字符串
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的字符串列表</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// var couponIds = new List&lt;string&gt; { "123", "", "456" };
        /// dict.AddIndexedArrayIfNotEmpty("coupon_id", couponIds);
        /// // 结果: coupon_id[0] = "123", coupon_id[1] = "456" (空字符串被过滤)
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArrayIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            List<string>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            // 过滤掉空字符串和null，同时记录有效元素的索引
            int index = 0;
            for (int i = 0; i < values.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(values[i]))
                {
                    dictionary[$"{keyPrefix}[{index}]"] = values[i];
                    index++;
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 当整数数组不为 null 且包含元素时，将其作为索引数组参数添加到字典中
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数数组</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArrayIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            int[]? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Length == 0)
                return dictionary;

            for (int i = 0; i < values.Length; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 当整数列表不为 null 且包含元素时，将其作为索引数组参数添加到字典中
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数列表</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArrayIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            List<int>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            for (int i = 0; i < values.Count; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 当 IList&lt;string&gt; 不为 null 且包含元素时，将其作为索引数组参数添加到字典中
        /// 过滤掉 null 和空白字符串
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的字符串列表接口</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArrayIfNotEmpty(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            IList<string>? values)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            // 过滤掉空字符串和null，同时记录有效元素的索引
            int index = 0;
            for (int i = 0; i < values.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(values[i]))
                {
                    dictionary[$"{keyPrefix}[{index}]"] = values[i];
                    index++;
                }
            }

            return dictionary;
        }

        #endregion

        #region 索引数组参数数值范围验证方法 (AOT 兼容)

        /// <summary>
        /// 当整数数组不为 null 且包含元素时，验证所有元素都大于指定最小值后添加到字典中
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数数组</param>
        /// <param name="minValue">最小值（不包含），默认为 0</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt;();
        /// dict.AddIndexedArrayIfAllGreaterThan("id", new[] { 1, 2, 3 }, 0);
        /// // 结果: id[0] = 1, id[1] = 2, id[2] = 3 (所有值都大于0)
        /// </code>
        /// </example>
        public static Dictionary<string, object> AddIndexedArrayIfAllGreaterThan(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            int[]? values,
            int minValue = 0)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Length == 0)
                return dictionary;

            // 检查所有值是否都大于最小值
            for (int i = 0; i < values.Length; i++)
            {
                if (values[i] <= minValue)
                    return dictionary; // 如果有任何值不符合条件，直接返回
            }

            // 所有值都符合条件，添加到字典
            for (int i = 0; i < values.Length; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        /// <summary>
        /// 当整数列表不为 null 且包含元素时，验证所有元素都大于指定最小值后添加到字典中
        /// </summary>
        /// <param name="dictionary">目标字典</param>
        /// <param name="keyPrefix">键名前缀（不包含方括号）</param>
        /// <param name="values">要添加的整数列表</param>
        /// <param name="minValue">最小值（不包含），默认为 0</param>
        /// <returns>返回字典本身，支持链式调用</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyPrefix 为 null 时抛出</exception>
        public static Dictionary<string, object> AddIndexedArrayIfAllGreaterThan(
            this Dictionary<string, object> dictionary,
            string keyPrefix,
            List<int>? values,
            int minValue = 0)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyPrefix);

            if (values is null || values.Count == 0)
                return dictionary;

            // 检查所有值是否都大于最小值
            for (int i = 0; i < values.Count; i++)
            {
                if (values[i] <= minValue)
                    return dictionary; // 如果有任何值不符合条件，直接返回
            }

            // 所有值都符合条件，添加到字典
            for (int i = 0; i < values.Count; i++)
            {
                dictionary[$"{keyPrefix}[{i}]"] = values[i];
            }

            return dictionary;
        }

        #endregion

        #region 基础值类型转换方法

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 Dictionary&lt;string, TValue&gt;
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <returns>转换后的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "age", 25 }, { "score", 100 } };
        /// var result = source.ToDictionary&lt;int&gt;();
        /// // 结果: Dictionary&lt;string, int&gt; { { "age", 25 }, { "score", 100 } }
        /// </code>
        /// </example>
        public static Dictionary<string, TValue> ToDictionary<TValue>(
            this Dictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new Dictionary<string, TValue>(dictionary.Count);
            foreach (var (key, value) in dictionary)
            {
                if (value is TValue typedValue)
                {
                    result[key] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }
            return result;
        }

        /// <summary>
        /// 将 SortedDictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;string, TValue&gt;
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <returns>转换后的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        public static SortedDictionary<string, TValue> ToSortedDictionary<TValue>(
            this SortedDictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new SortedDictionary<string, TValue>();
            foreach (var (key, value) in dictionary)
            {
                if (value is TValue typedValue)
                {
                    result[key] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }
            return result;
        }

        /// <summary>
        /// 安全地将 Dictionary&lt;string, object&gt; 转换为 Dictionary&lt;string, TValue&gt;
        /// 转换失败的项会被跳过
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <returns>转换后的字典（只包含成功转换的项）</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "age", 25 }, { "name", "John" } };
        /// var result = source.ToDictionarySafe&lt;int&gt;();
        /// // 结果: Dictionary&lt;string, int&gt; { { "age", 25 } } (name 被跳过)
        /// </code>
        /// </example>
        public static Dictionary<string, TValue> ToDictionarySafe<TValue>(
            this Dictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new Dictionary<string, TValue>();
            foreach (var (key, value) in dictionary)
            {
                try
                {
                    if (value is TValue typedValue)
                    {
                        result[key] = typedValue;
                    }
                    else if (value is IConvertible)
                    {
                        result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                }
                catch
                {
                    // 忽略转换失败的项
                }
            }
            return result;
        }

        /// <summary>
        /// 安全地将 SortedDictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;string, TValue&gt;
        /// 转换失败的项会被跳过
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <returns>转换后的字典（只包含成功转换的项）</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static SortedDictionary<string, TValue> ToSortedDictionarySafe<TValue>(
            this SortedDictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new SortedDictionary<string, TValue>();
            foreach (var (key, value) in dictionary)
            {
                try
                {
                    if (value is TValue typedValue)
                    {
                        result[key] = typedValue;
                    }
                    else if (value is IConvertible)
                    {
                        result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                }
                catch
                {
                    // 忽略转换失败的项
                }
            }
            return result;
        }

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 Dictionary&lt;string, TValue&gt;
        /// 转换失败时使用指定的默认值
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="defaultValue">转换失败时使用的默认值</param>
        /// <returns>转换后的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "age", 25 }, { "name", "John" } };
        /// var result = source.ToDictionary&lt;int&gt;(0);
        /// // 结果: Dictionary&lt;string, int&gt; { { "age", 25 }, { "name", 0 } }
        /// </code>
        /// </example>
        public static Dictionary<string, TValue> ToDictionary<TValue>(
            this Dictionary<string, object> dictionary,
            TValue defaultValue)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new Dictionary<string, TValue>(dictionary.Count);
            foreach (var (key, value) in dictionary)
            {
                try
                {
                    if (value is TValue typedValue)
                    {
                        result[key] = typedValue;
                    }
                    else if (value is IConvertible)
                    {
                        result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        result[key] = defaultValue;
                    }
                }
                catch
                {
                    result[key] = defaultValue;
                }
            }
            return result;
        }

        /// <summary>
        /// 将 SortedDictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;string, TValue&gt;
        /// 转换失败时使用指定的默认值
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="defaultValue">转换失败时使用的默认值</param>
        /// <returns>转换后的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static SortedDictionary<string, TValue> ToSortedDictionary<TValue>(
            this SortedDictionary<string, object> dictionary,
            TValue defaultValue)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new SortedDictionary<string, TValue>();
            foreach (var (key, value) in dictionary)
            {
                try
                {
                    if (value is TValue typedValue)
                    {
                        result[key] = typedValue;
                    }
                    else if (value is IConvertible)
                    {
                        result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        result[key] = defaultValue;
                    }
                }
                catch
                {
                    result[key] = defaultValue;
                }
            }
            return result;
        }

        #endregion

        #region 键类型转换方法

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 Dictionary&lt;TKey, TValue&gt;
        /// 使用自定义的键转换函数
        /// </summary>
        /// <typeparam name="TKey">目标键类型</typeparam>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="keyConverter">键转换函数</param>
        /// <returns>转换后的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyConverter 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "1", 100 }, { "2", 200 } };
        /// var result = source.ToDictionary&lt;int, int&gt;(key => int.Parse(key));
        /// // 结果: Dictionary&lt;int, int&gt; { { 1, 100 }, { 2, 200 } }
        /// </code>
        /// </example>
        public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(
            this Dictionary<string, object> dictionary,
            Func<string, TKey> keyConverter) where TKey : notnull
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyConverter);
            var result = new Dictionary<TKey, TValue>(dictionary.Count);
            foreach (var (key, value) in dictionary)
            {
                var convertedKey = keyConverter(key);
                if (value is TValue typedValue)
                {
                    result[convertedKey] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[convertedKey] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }
            return result;
        }

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 Dictionary&lt;TKey, TValue&gt;
        /// 使用自定义的键和值转换函数
        /// </summary>
        /// <typeparam name="TKey">目标键类型</typeparam>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="keyConverter">键转换函数</param>
        /// <param name="valueConverter">值转换函数</param>
        /// <returns>转换后的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、keyConverter 或 valueConverter 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "1", "100" }, { "2", "200" } };
        /// var result = source.ToDictionary&lt;int, int&gt;(
        ///     key => int.Parse(key),
        ///     value => int.Parse(value.ToString()!));
        /// // 结果: Dictionary&lt;int, int&gt; { { 1, 100 }, { 2, 200 } }
        /// </code>
        /// </example>
        public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(
            this Dictionary<string, object> dictionary,
            Func<string, TKey> keyConverter,
            Func<object, TValue> valueConverter) where TKey : notnull
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyConverter);
            ArgumentNullException.ThrowIfNull(valueConverter);
            var result = new Dictionary<TKey, TValue>(dictionary.Count);
            foreach (var (key, value) in dictionary)
            {
                var convertedKey = keyConverter(key);
                var convertedValue = valueConverter(value);
                result[convertedKey] = convertedValue;
            }
            return result;
        }

        /// <summary>
        /// 将 SortedDictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;TKey, TValue&gt;
        /// 使用自定义的键转换函数
        /// </summary>
        /// <typeparam name="TKey">目标键类型</typeparam>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="keyConverter">键转换函数</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyConverter 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        /// <example>
        /// <code>
        /// var sorted = new SortedDictionary&lt;string, object&gt; { { "2", 200 }, { "1", 100 } };
        /// var result = sorted.ToSortedDictionary&lt;int, int&gt;(key => int.Parse(key));
        /// // 结果: SortedDictionary&lt;int, int&gt; { { 1, 100 }, { 2, 200 } }
        /// </code>
        /// </example>
        public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(
            this SortedDictionary<string, object> dictionary,
            Func<string, TKey> keyConverter,
            IComparer<TKey>? comparer = null) where TKey : notnull
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyConverter);

            var result = comparer is null
                ? []
                : new SortedDictionary<TKey, TValue>(comparer);

            foreach (var (key, value) in dictionary)
            {
                var convertedKey = keyConverter(key);

                if (value is TValue typedValue)
                {
                    result[convertedKey] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[convertedKey] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }

            return result;
        }

        /// <summary>
        /// 将 SortedDictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;TKey, TValue&gt;
        /// 使用自定义的键和值转换函数
        /// </summary>
        /// <typeparam name="TKey">目标键类型</typeparam>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="keyConverter">键转换函数</param>
        /// <param name="valueConverter">值转换函数</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、keyConverter 或 valueConverter 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var sorted = new SortedDictionary&lt;string, object&gt; { { "2", "200" }, { "1", "100" } };
        /// var result = sorted.ToSortedDictionary&lt;int, int&gt;(
        ///     key => int.Parse(key),
        ///     value => int.Parse(value.ToString()!));
        /// // 结果: SortedDictionary&lt;int, int&gt; { { 1, 100 }, { 2, 200 } }
        /// </code>
        /// </example>
        public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(
            this SortedDictionary<string, object> dictionary,
            Func<string, TKey> keyConverter,
            Func<object, TValue> valueConverter,
            IComparer<TKey>? comparer = null) where TKey : notnull
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyConverter);
            ArgumentNullException.ThrowIfNull(valueConverter);

            var result = comparer is null
                ? []
                : new SortedDictionary<TKey, TValue>(comparer);

            foreach (var (key, value) in dictionary)
            {
                var convertedKey = keyConverter(key);
                var convertedValue = valueConverter(value);
                result[convertedKey] = convertedValue;
            }

            return result;
        }

        #endregion

        #region Dictionary 与 SortedDictionary 相互转换

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;string, object&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; { { "b", 2 }, { "a", 1 } };
        /// var sorted = dict.ToSortedDictionary();
        /// // 结果: 按键字母顺序排序 { { "a", 1 }, { "b", 2 } }
        /// </code>
        /// </example>
        public static SortedDictionary<string, object> ToSortedDictionary(
            this Dictionary<string, object> dictionary,
            IComparer<string>? comparer = null)
        {
            ArgumentNullException.ThrowIfNull(dictionary);

            var result = comparer is null
                ? []
                : new SortedDictionary<string, object>(comparer);

            foreach (var (key, value) in dictionary)
            {
                result[key] = value;
            }

            return result;
        }

        /// <summary>
        /// 将 SortedDictionary&lt;string, object&gt; 转换为 Dictionary&lt;string, object&gt;
        /// </summary>
        /// <param name="sortedDictionary">源有序字典</param>
        /// <returns>普通字典</returns>
        /// <exception cref="ArgumentNullException">当 sortedDictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var sorted = new SortedDictionary&lt;string, object&gt; { { "a", 1 }, { "b", 2 } };
        /// var dict = sorted.ToDictionary();
        /// // 结果: Dictionary&lt;string, object&gt;
        /// </code>
        /// </example>
        public static Dictionary<string, object> ToDictionary(
            this SortedDictionary<string, object> sortedDictionary)
        {
            ArgumentNullException.ThrowIfNull(sortedDictionary);

            var result = new Dictionary<string, object>(sortedDictionary.Count);

            foreach (var (key, value) in sortedDictionary)
            {
                result[key] = value;
            }

            return result;
        }

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;string, TValue&gt;
        /// 同时进行值类型转换
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; { { "b", "2" }, { "a", "1" } };
        /// var sorted = dict.ToSortedDictionary&lt;int&gt;();
        /// // 结果: SortedDictionary&lt;string, int&gt; { { "a", 1 }, { "b", 2 } }
        /// </code>
        /// </example>
        public static SortedDictionary<string, TValue> ToSortedDictionary<TValue>(
            this Dictionary<string, object> dictionary,
            IComparer<string>? comparer = null)
        {
            ArgumentNullException.ThrowIfNull(dictionary);

            var result = comparer is null
                ? []
                : new SortedDictionary<string, TValue>(comparer);

            foreach (var (key, value) in dictionary)
            {
                if (value is TValue typedValue)
                {
                    result[key] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }

            return result;
        }

        /// <summary>
        /// 将 SortedDictionary&lt;string, object&gt; 转换为 Dictionary&lt;string, TValue&gt;
        /// 同时进行值类型转换
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="sortedDictionary">源有序字典</param>
        /// <returns>普通字典</returns>
        /// <exception cref="ArgumentNullException">当 sortedDictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        /// <example>
        /// <code>
        /// var sorted = new SortedDictionary&lt;string, object&gt; { { "a", 1 }, { "b", 2 } };
        /// var dict = sorted.ToDictionary&lt;int&gt;();
        /// // 结果: Dictionary&lt;string, int&gt; { { "a", 1 }, { "b", 2 } }
        /// </code>
        /// </example>
        public static Dictionary<string, TValue> ToDictionary<TValue>(
            this SortedDictionary<string, object> sortedDictionary)
        {
            ArgumentNullException.ThrowIfNull(sortedDictionary);

            var result = new Dictionary<string, TValue>(sortedDictionary.Count);

            foreach (var (key, value) in sortedDictionary)
            {
                if (value is TValue typedValue)
                {
                    result[key] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }

            return result;
        }

        /// <summary>
        /// 安全地将 Dictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;string, TValue&gt;
        /// 转换失败的项会被跳过
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典（只包含成功转换的项）</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static SortedDictionary<string, TValue> ToSortedDictionarySafe<TValue>(
            this Dictionary<string, object> dictionary,
            IComparer<string>? comparer = null)
        {
            ArgumentNullException.ThrowIfNull(dictionary);

            var result = comparer is null
                ? []
                : new SortedDictionary<string, TValue>(comparer);

            foreach (var (key, value) in dictionary)
            {
                try
                {
                    if (value is TValue typedValue)
                    {
                        result[key] = typedValue;
                    }
                    else if (value is IConvertible)
                    {
                        result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                }
                catch
                {
                    // 忽略转换失败的项
                }
            }

            return result;
        }

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;TKey, TValue&gt;
        /// 同时转换键和值类型
        /// </summary>
        /// <typeparam name="TKey">目标键类型</typeparam>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="keyConverter">键转换函数</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 keyConverter 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为目标类型时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; { { "2", 200 }, { "1", 100 } };
        /// var sorted = dict.ToSortedDictionary&lt;int, int&gt;(key => int.Parse(key));
        /// // 结果: SortedDictionary&lt;int, int&gt; { { 1, 100 }, { 2, 200 } }
        /// </code>
        /// </example>
        public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(
            this Dictionary<string, object> dictionary,
            Func<string, TKey> keyConverter,
            IComparer<TKey>? comparer = null) where TKey : notnull
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyConverter);

            var result = comparer is null
                ? []
                : new SortedDictionary<TKey, TValue>(comparer);

            foreach (var (key, value) in dictionary)
            {
                var convertedKey = keyConverter(key);

                if (value is TValue typedValue)
                {
                    result[convertedKey] = typedValue;
                }
                else if (value is IConvertible)
                {
                    result[convertedKey] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new InvalidCastException($"无法将键 '{key}' 的值从 {value?.GetType().Name ?? "null"} 转换为 {typeof(TValue).Name}");
                }
            }

            return result;
        }

        /// <summary>
        /// 将 Dictionary&lt;string, object&gt; 转换为 SortedDictionary&lt;TKey, TValue&gt;
        /// 使用自定义的键和值转换函数
        /// </summary>
        /// <typeparam name="TKey">目标键类型</typeparam>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="keyConverter">键转换函数</param>
        /// <param name="valueConverter">值转换函数</param>
        /// <param name="comparer">可选的键比较器</param>
        /// <returns>有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary、keyConverter 或 valueConverter 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; { { "2", "200" }, { "1", "100" } };
        /// var sorted = dict.ToSortedDictionary&lt;int, int&gt;(
        ///     key => int.Parse(key),
        ///     value => int.Parse(value.ToString()!));
        /// // 结果: SortedDictionary&lt;int, int&gt; { { 1, 100 }, { 2, 200 } }
        /// </code>
        /// </example>
        public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(
            this Dictionary<string, object> dictionary,
            Func<string, TKey> keyConverter,
            Func<object, TValue> valueConverter,
            IComparer<TKey>? comparer = null) where TKey : notnull
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(keyConverter);
            ArgumentNullException.ThrowIfNull(valueConverter);

            var result = comparer is null
                ? []
                : new SortedDictionary<TKey, TValue>(comparer);

            foreach (var (key, value) in dictionary)
            {
                var convertedKey = keyConverter(key);
                var convertedValue = valueConverter(value);
                result[convertedKey] = convertedValue;
            }

            return result;
        }

        #endregion

        #region 常用类型转换便捷方法

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, string&gt;
        /// 使用 ToString() 方法转换所有值
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>字符串字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "age", 25 }, { "name", "John" } };
        /// var result = source.ToStringDictionary();
        /// // 结果: Dictionary&lt;string, string&gt; { { "age", "25" }, { "name", "John" } }
        /// </code>
        /// </example>
        public static Dictionary<string, string> ToStringDictionary(
            this Dictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new Dictionary<string, string>(dictionary.Count);
            foreach (var (key, value) in dictionary)
            {
                result[key] = value?.ToString() ?? string.Empty;
            }
            return result;
        }

        /// <summary>
        /// 将字典转换为 SortedDictionary&lt;string, string&gt;
        /// 使用 ToString() 方法转换所有值
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>字符串有序字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static SortedDictionary<string, string> ToStringDictionary(
            this SortedDictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            var result = new SortedDictionary<string, string>();
            foreach (var (key, value) in dictionary)
            {
                result[key] = value?.ToString() ?? string.Empty;
            }
            return result;
        }

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, int&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>整数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 int 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "age", 25 }, { "score", "100" } };
        /// var result = source.ToIntDictionary();
        /// // 结果: Dictionary&lt;string, int&gt; { { "age", 25 }, { "score", 100 } }
        /// </code>
        /// </example>
        public static Dictionary<string, int> ToIntDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToDictionary<int>();
        }

        /// <summary>
        /// 安全地将字典转换为 Dictionary&lt;string, int&gt;
        /// 转换失败时使用默认值
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <param name="defaultValue">转换失败时使用的默认值，默认为 0</param>
        /// <returns>整数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static Dictionary<string, int> ToIntDictionary(
            this Dictionary<string, object> dictionary,
            int defaultValue = 0)
        {
            return dictionary.ToDictionary(defaultValue);
        }

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, long&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>长整数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 long 时抛出</exception>
        public static Dictionary<string, long> ToLongDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToDictionary<long>();
        }

        /// <summary>
        /// 安全地将字典转换为 Dictionary&lt;string, long&gt;
        /// 转换失败时使用默认值
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <param name="defaultValue">转换失败时使用的默认值，默认为 0</param>
        /// <returns>长整数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static Dictionary<string, long> ToLongDictionary(
            this Dictionary<string, object> dictionary,
            long defaultValue = 0L)
        {
            return dictionary.ToDictionary(defaultValue);
        }

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, decimal&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>小数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 decimal 时抛出</exception>
        public static Dictionary<string, decimal> ToDecimalDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToDictionary<decimal>();
        }

        /// <summary>
        /// 安全地将字典转换为 Dictionary&lt;string, decimal&gt;
        /// 转换失败时使用默认值
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <param name="defaultValue">转换失败时使用的默认值，默认为 0</param>
        /// <returns>小数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        public static Dictionary<string, decimal> ToDecimalDictionary(
            this Dictionary<string, object> dictionary,
            decimal defaultValue = 0m)
        {
            return dictionary.ToDictionary(defaultValue);
        }

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, bool&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>布尔字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 bool 时抛出</exception>
        public static Dictionary<string, bool> ToBoolDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToDictionary<bool>();
        }

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, DateTime&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>日期时间字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 DateTime 时抛出</exception>
        public static Dictionary<string, DateTime> ToDateTimeDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToDictionary<DateTime>();
        }

        /// <summary>
        /// 将字典转换为 Dictionary&lt;string, Guid&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>GUID字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 Guid 时抛出</exception>
        public static Dictionary<string, Guid> ToGuidDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToDictionary<Guid>();
        }

        #endregion

        #region 常用排序场景的便捷方法

        /// <summary>
        /// 将字典转换为按键名称排序的 SortedDictionary&lt;string, string&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>按键排序的字符串字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; 
        /// { 
        ///     { "name", "John" }, 
        ///     { "age", 25 } 
        /// };
        /// var sorted = dict.ToSortedStringDictionary();
        /// // 结果: 按字母顺序 { { "age", "25" }, { "name", "John" } }
        /// </code>
        /// </example>
        public static SortedDictionary<string, string> ToSortedStringDictionary(
            this Dictionary<string, object> dictionary)
        {
            ArgumentNullException.ThrowIfNull(dictionary);

            var result = new SortedDictionary<string, string>();

            foreach (var (key, value) in dictionary)
            {
                result[key] = value?.ToString() ?? string.Empty;
            }

            return result;
        }

        /// <summary>
        /// 将字典转换为按键名称排序的 SortedDictionary&lt;string, int&gt;
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>按键排序的整数字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <exception cref="InvalidCastException">当值无法转换为 int 时抛出</exception>
        public static SortedDictionary<string, int> ToSortedIntDictionary(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToSortedDictionary<int>();
        }

        /// <summary>
        /// 使用忽略大小写的字符串比较器创建排序字典
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>忽略大小写排序的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; 
        /// { 
        ///     { "Name", 1 }, 
        ///     { "age", 2 }, 
        ///     { "ADDRESS", 3 } 
        /// };
        /// var sorted = dict.ToSortedDictionaryIgnoreCase();
        /// // 结果: 按忽略大小写的字母顺序排序
        /// </code>
        /// </example>
        public static SortedDictionary<string, object> ToSortedDictionaryIgnoreCase(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToSortedDictionary(StringComparer.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 使用自然排序（数字部分按数值排序）创建排序字典
        /// </summary>
        /// <param name="dictionary">源字典</param>
        /// <returns>自然排序的字典</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var dict = new Dictionary&lt;string, object&gt; 
        /// { 
        ///     { "item10", 1 }, 
        ///     { "item2", 2 }, 
        ///     { "item1", 3 } 
        /// };
        /// var sorted = dict.ToSortedDictionaryNatural();
        /// // 结果: item1, item2, item10 (而不是 item1, item10, item2)
        /// </code>
        /// </example>
        public static SortedDictionary<string, object> ToSortedDictionaryNatural(
            this Dictionary<string, object> dictionary)
        {
            return dictionary.ToSortedDictionary(new NaturalStringComparer());
        }

        #endregion

        #region 高级转换方法

        /// <summary>
        /// 使用自定义条件过滤并转换字典
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="predicate">过滤条件</param>
        /// <returns>转换后的字典（只包含满足条件的项）</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 或 predicate 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; 
        /// { 
        ///     { "age", 25 }, 
        ///     { "score", 100 },
        ///     { "name", "John" }
        /// };
        /// var result = source.ToDictionaryWhere&lt;int&gt;(
        ///     kvp => kvp.Value is int || (kvp.Value is string s &amp;&amp; int.TryParse(s, out _)));
        /// // 结果: Dictionary&lt;string, int&gt; { { "age", 25 }, { "score", 100 } }
        /// </code>
        /// </example>
        public static Dictionary<string, TValue> ToDictionaryWhere<TValue>(
            this Dictionary<string, object> dictionary,
            Func<KeyValuePair<string, object>, bool> predicate)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            ArgumentNullException.ThrowIfNull(predicate);
            var result = new Dictionary<string, TValue>();
            foreach (var kvp in dictionary.Where(predicate))
            {
                try
                {
                    if (kvp.Value is TValue typedValue)
                    {
                        result[kvp.Key] = typedValue;
                    }
                    else if (kvp.Value is IConvertible)
                    {
                        result[kvp.Key] = (TValue)Convert.ChangeType(kvp.Value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                }
                catch
                {
                    // 忽略转换失败的项
                }
            }
            return result;
        }

        /// <summary>
        /// 尝试将字典转换为指定类型，返回是否成功
        /// </summary>
        /// <typeparam name="TValue">目标值类型</typeparam>
        /// <param name="dictionary">源字典</param>
        /// <param name="result">转换结果</param>
        /// <returns>如果所有项都成功转换返回 true，否则返回 false</returns>
        /// <exception cref="ArgumentNullException">当 dictionary 为 null 时抛出</exception>
        /// <example>
        /// <code>
        /// var source = new Dictionary&lt;string, object&gt; { { "age", 25 }, { "score", 100 } };
        /// if (source.TryToDictionary&lt;int&gt;(out var result))
        /// {
        ///     // 所有值都成功转换为 int
        /// }
        /// </code>
        /// </example>
        public static bool TryToDictionary<TValue>(
            this Dictionary<string, object> dictionary,
            out Dictionary<string, TValue> result)
        {
            ArgumentNullException.ThrowIfNull(dictionary);
            result = new Dictionary<string, TValue>(dictionary.Count);
            try
            {
                foreach (var (key, value) in dictionary)
                {
                    if (value is TValue typedValue)
                    {
                        result[key] = typedValue;
                    }
                    else if (value is IConvertible)
                    {
                        result[key] = (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        result = [];
                        return false;
                    }
                }
                return true;
            }
            catch
            {
                result = [];
                return false;
            }
        }

        #endregion

        #region 自然排序比较器

        /// <summary>
        /// 自然字符串比较器（数字部分按数值排序）
        /// 例如：item1, item2, item10 而不是 item1, item10, item2
        /// </summary>
        private sealed class NaturalStringComparer : IComparer<string>
        {
            public int Compare(string? x, string? y)
            {
                if (x == y) return 0;
                if (x is null) return -1;
                if (y is null) return 1;

                int ix = 0, iy = 0;

                while (ix < x.Length && iy < y.Length)
                {
                    // 检查是否是数字
                    if (char.IsDigit(x[ix]) && char.IsDigit(y[iy]))
                    {
                        // 提取数字部分
                        int numX = 0, numY = 0;

                        while (ix < x.Length && char.IsDigit(x[ix]))
                        {
                            numX = numX * 10 + (x[ix] - '0');
                            ix++;
                        }

                        while (iy < y.Length && char.IsDigit(y[iy]))
                        {
                            numY = numY * 10 + (y[iy] - '0');
                            iy++;
                        }

                        if (numX != numY)
                            return numX.CompareTo(numY);
                    }
                    else
                    {
                        // 非数字部分按字符比较
                        int result = x[ix].CompareTo(y[iy]);
                        if (result != 0)
                            return result;

                        ix++;
                        iy++;
                    }
                }

                // 长度不同时，短的排在前面
                return x.Length.CompareTo(y.Length);
            }
        }

        #endregion
    }
}